import React, { useState, useEffect } from 'react'
import { Menu } from "antd"
import localMenus from "@/config/menuConfig.js"


/**
 * 用户登录成功,访问菜单userInfo menus = ["/home/","/home/user","/home/role"]
 * 和本地的菜单进行比较,匹配可以访问.否则不能访问
 * @returns 
 */
export default function MyMenu() {
    //动态菜单的逻辑
    const [userInfo, setUserInfo] = useState({ role: {} })
    useEffect(() => {
        const info = JSON.parse(localStorage.userInfo || "{}")
        setUserInfo(info)
    }, [])
    const menuClick = (p1)=>{
        console.log(p1);
        console.log(p1.domEvent.target);
    }

    //initMenu返回什么菜单,页面智能渲染哪些菜单
    //半选状态,是添加父级
    // const initMenu = (array, news = []) => {
    //     //这个函数,return中进来调用.执行时候,userInfo还没有赋值完成
    //     const { menus } = userInfo.role
    //     for (const item of array) {
    //         if (menus && menus.includes(item.key)) {
    //             if (!item.children) {
    //                 news.push(item)
    //             }else{
    //                 let node = {...item,children:[]}
    //                 news.push(node)
    //                 initMenu(item.children,node.children)
    //             }
    //         }
    //     }
    //     return news
    // }
    const initMenu = (array, news = []) => {
        //解构代码的时候.设置默认值
        const { menus=[] } = userInfo.role
        for (const item of array) {
            if(!item.children){
                if(menus.includes(item.key)){
                    news.push(item)
                }
            }else{
                let node = {...item,children:[]}
                initMenu(item.children,node.children)
                if(node.children.length){
                    news.push(node)
                }
            }
        }
        return news

    }
    return (
        <Menu
            theme="dark"
            defaultSelectedKeys={['/home/']}
            defaultOpenKeys={["/home/product", "/home/chart"]}
            mode="inline"
            items={initMenu(localMenus)}
            onClick={menuClick}
        />
    )
}
